package com.yinhai.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.lz.util.Utils;
import com.lz.views.LoadingDialog;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.asynctask.LoginTask;
import com.yinhai.asynctask.NameValueParam;
import com.yinhai.constant.Contact;
import com.yinhai.constant.UrlConstant;
import com.yinhai.map.ServiceMap;
import com.yinhai.receiver.SyncContactService;
import com.yinhai.service.CloudNoteServiceImpl;
import com.yinhai.util.DateUtil;
import com.yinhai.util.IMSI;
import com.yinhai.util.UuId;

public class LoginValidateYZM extends Activity {
    
    private EditText yzm;
    
    private EditText password;
    
    private Button btn, btnsy, btnyzm;
    private SharedPreferences sharedPreferences;
    
    private Button cancle;
    
    private Context context;
    
    AlertDialog.Builder dialog;
    
    private long exitTime = 0;
    
    private ImageView btn_back;
    
    String userName;
    
    private AQuery aq;
    
    private String msgyzm = "";
    
    private TimeCount t;
    
    private BroadcastReceiver smsReceiver;
    
    private String localString = "欢迎使用中国移动集团通信录，本次注册验证码为:";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.main_login_validate_yzm);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        smsReceiver = new SMSReceiver();
        registerReceiver(smsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
        yzm = (EditText)this.findViewById(R.id.userName);
        password = (EditText)this.findViewById(R.id.password);
        btn = (Button)this.findViewById(R.id.btn);
        btnsy = (Button)this.findViewById(R.id.btnsy);
        cancle = (Button)this.findViewById(R.id.cancle);
        btn_back = (ImageView)findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        
        aq = new AQuery(this);
        
        Intent it = getIntent();
        userName = it.getStringExtra("USERNAME");
        t = new TimeCount(120000, 1000);// 构造CountDownTimer对象
        btnyzm = (Button)findViewById(R.id.btnyzm);
        /**
         * 限制输入框换行
         */
        yzm.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
        /**
         * 获取验证码
         */
        aq.id(R.id.btnyzm).clicked(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                t.start();
                LoadingDialog dialog = new LoadingDialog(context, "正在获取验证码...");
                String url = UrlConstant.LOCAL_URI + "getValidateCode?phone=" + userName;
                aq.progress(dialog).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
                    @Override
                    public void callback(String url, JSONObject json, AjaxStatus status) {
                        if (json != null) {
                            try {
                                int flag = json.getInt("flag");
                                if (flag == 1) {
                                    msgyzm = json.getString("msg");
                                } else {
                                    Utils.showToast(context, json.getString("msg"));
                                }
                                Log.i("==yzm==", json.toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        
                    }
                });
                
            }
        });
        
        /*
         * if(!userName.equals("")){
         * 
         * }
         */
        
        /**
         * 判断验证码是否有效
         */
        
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String userNameStr = yzm.getText() == null ? "" : yzm.getText().toString().trim();
                
                if (userNameStr.equals("")) {
                    Utils.showToast(context, "验证码不能为空");
                    return;
                }
                
                String url = UrlConstant.LOCAL_URI + "validateCode?phone=" + userName + "&randCode=" + userNameStr;
                aq.progress(0).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
                    @Override
                    public void callback(String url, JSONObject json, AjaxStatus status) {
                        if (json != null) {
                            try {
                                int flag = json.getInt("flag");
                                if (flag == 1) {
                                    LoadDengLu();
                                } else {
                                    Utils.showToast(context, json.getString("msg"));
                                }
                                // Log.i("==yzmaaaaaa==", json.toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        
                    }
                });
                
            }
        });
        
        cancle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                
                dialog = new AlertDialog.Builder(LoginValidateYZM.this);
                
                dialog.setTitle("提示")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage("确认退出！")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    })
                    .create();
                dialog.show();
                
            }
        });
        registerReceiver(loginreceiver, new IntentFilter("com.gaa.login"));
    }
    
    /* 定义一个倒计时的内部类 */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }
        
        @Override
        public void onFinish() {// 计时完毕时触发
            btnyzm.setText("重新验证");
            btnyzm.setClickable(true);
        }
        
        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            btnyzm.setClickable(false);
            btnyzm.setText(millisUntilFinished / 1000 + "秒");
        }
    }
    
    /**
     * 注册 提交
     */
    private void LoadDengLu() {
        
        LoginTask loginTask = new LoginTask(context);
        loginTask.setUserNamePhone(userName);
        AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.LOCAL_URI + UrlConstant.CHECK);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        NameValueParam user_phone = new NameValueParam();
        NameValueParam first = new NameValueParam();
        first.setName("first");
        // 第一次登录验证
        first.setValue("0");
        user_phone.setName("user_phone");
        user_phone.setValue(userName);
        NameValueParam imsinvp = new NameValueParam();
        NameValueParam flagnvp = new NameValueParam();
        String imsi = "";
        String flag = "";
        if (IMSI.getIMSI(context) != null) {
            imsi = IMSI.getIMSI(context);
            flag = "1";
        } else {
            imsi = UuId.getUUID();
            flag = "0";
        }
        imsinvp.setName("sim");
        imsinvp.setValue(imsi);
        flagnvp.setName("flag");
        flagnvp.setValue(flag);
        list.add(imsinvp);
        list.add(flagnvp);
        list.add(first);
        list.add(user_phone);
        taskParam.setPostParam(list);
        loginTask.execute(taskParam);
//        try{
//        	 Intent syncContactIntent = new Intent(LoginValidateYZM.this, SyncContactService.class);
//        	 syncContactIntent.putExtra("phone", userName);
//             startService(syncContactIntent);
//             ServiceMap.getMap().put(Contact.SYNC_CONTACT_SERVICE, syncContactIntent);
//             Editor editor = sharedPreferences.edit();
//             editor.putLong("onLineUpdateTime", System.currentTimeMillis());
//             editor.putString("onLineContactLastUpdateTime",
//                 DateUtil.dateFormatString(new Date(), DateUtil.DAY_TIME_FORMATE));
//             editor.commit();
//        } catch(Exception e) {
//        	
//        }
       
        runOnUiThread(new Runnable() {
            
            @Override
            public void run() {
                CloudNoteServiceImpl cloudNoteService = new CloudNoteServiceImpl(LoginValidateYZM.this);
                cloudNoteService.deleteAllCloudNote();
            }
        });
        
    }
    
    private BroadcastReceiver loginreceiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.gaa.login")) {
                finish();
            }
            
        }
    };
    
    @Override
    public void onDestroy() {
        unregisterReceiver(loginreceiver);
        unregisterReceiver(smsReceiver);
        super.onDestroy();
    }
    
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }
    
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
            // exit();
            finish();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
    
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast toast = Toast.makeText(getApplicationContext(), "再按一次后退键退出应用程序", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            exitTime = System.currentTimeMillis();
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
    
    /**
     * 短信接收监听
     * 
     * @author Administrator
     *
     */
    public class SMSReceiver extends BroadcastReceiver {
        // private Context mContext;
        // private static final String TAG = "REC_TEST";
        
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            SmsMessage[] smsMessages = null;
            Object[] pdus = null;
            if (bundle != null) {
                pdus = (Object[])bundle.get("pdus");
            }
            if (pdus != null) {
                smsMessages = new SmsMessage[pdus.length];
                String sender = null;
                String content = null;
                for (int i = 0; i < pdus.length; i++) {
                    smsMessages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                    sender = smsMessages[i].getOriginatingAddress();
                    content = smsMessages[i].getMessageBody();
                }
                if (content != null && content.contains("欢迎使用中国移动集团通信录，本次注册验证码为:")) {
                    if ((content.length() - localString.length()) == 4) {
                        try {
                            content = content.substring(localString.length(), localString.length() + 4);
                            yzm.setText(content.trim());
                        } catch (Exception e) {
                            
                        }
                        
                    }
                }
            }
        }
    }
}
